{% extends "base.html" %}

{% block title %}用户管理 - 风之宿{% endblock %}

{% block extra_css %}
<style type="text/tailwindcss">
@layer utilities {
    .modal-overlay {
        @apply fixed inset-0 bg-black bg-opacity-50 z-50 hidden;
    }
    .modal-overlay.active {
        @apply flex items-center justify-center;
    }
    .modal-content {
        @apply bg-white rounded-xl shadow-2xl max-w-md w-full mx-4 transform transition-all;
    }
    .user-card {
        @apply bg-white rounded-xl shadow-lg hover:shadow-xl transition-all duration-300;
    }
    .badge {
        @apply px-3 py-1 rounded-full text-xs font-semibold;
    }
    .badge-user {
        @apply bg-gradient-to-r from-blue-100 to-blue-200 text-blue-800;
    }
    .badge-admin {
        @apply bg-gradient-to-r from-purple-100 to-purple-200 text-purple-800;
    }
    .table-row {
        @apply hover:bg-gradient-to-r hover:from-blue-50 hover:to-transparent transition-all duration-200;
    }
}
</style>
{% endblock %}

{% block content %}
<div class="container mx-auto px-4 py-8">
  <!-- 页面标题 -->
  <div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-8 bg-gradient-to-r from-blue-50 to-purple-50 p-6 rounded-xl shadow-md">
    <div>
      <h1 class="text-3xl font-bold text-primary mb-2">
        <i class="fas fa-users mr-2"></i>用户管理
      </h1>
      <p class="text-gray-600">管理系统用户信息和权限</p>
    </div>
    <div class="text-right mt-4 md:mt-0">
      <p class="text-sm text-gray-500 mb-1">总用户数</p>
      <p class="text-3xl font-bold text-primary">{{ total_items }}</p>
    </div>
  </div>

  <!-- 搜索和筛选 -->
  <div class="bg-white rounded-xl shadow-md p-6 mb-6">
    <form method="GET" action="{{ url_for('admin.manage_users') }}" class="flex flex-wrap gap-4">
      <div class="flex-1 min-w-[200px]">
        <label class="block text-sm font-semibold text-gray-700 mb-2">
          <i class="fas fa-search text-primary mr-1"></i>搜索用户
        </label>
        <input type="text" name="search" value="{{ search_query }}" 
               placeholder="输入用户名、邮箱或电话"
               class="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent transition-all">
      </div>
      <div class="min-w-[150px]">
        <label class="block text-sm font-semibold text-gray-700 mb-2">
          <i class="fas fa-filter text-primary mr-1"></i>角色筛选
        </label>
        <select name="role" class="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary">
          <option value="all" {% if role_filter == 'all' %}selected{% endif %}>所有角色</option>
          <option value="user" {% if role_filter == 'user' %}selected{% endif %}>👤 用户</option>
          <option value="admin" {% if role_filter == 'admin' %}selected{% endif %}>🔑 管理员</option>
        </select>
      </div>
      <div class="flex items-end gap-2">
        <button type="submit" class="px-6 py-2.5 bg-gradient-to-r from-primary to-accent text-white rounded-lg hover:shadow-lg transition-all">
          <i class="fas fa-search mr-2"></i>搜索
        </button>
        <a href="{{ url_for('admin.manage_users') }}" class="px-6 py-2.5 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition-all">
          <i class="fas fa-redo mr-2"></i>重置
        </a>
      </div>
    </form>
  </div>

  <!-- 用户列表 -->
  <div class="user-card overflow-hidden">
    {% if users %}
    <div class="overflow-x-auto">
      <table class="min-w-full divide-y divide-gray-200">
        <thead class="bg-gradient-to-r from-primary to-accent text-white">
          <tr>
            <th class="px-6 py-4 text-left text-xs font-bold uppercase tracking-wider">用户信息</th>
            <th class="px-6 py-4 text-left text-xs font-bold uppercase tracking-wider">联系方式</th>
            <th class="px-6 py-4 text-left text-xs font-bold uppercase tracking-wider">角色</th>
            <th class="px-6 py-4 text-left text-xs font-bold uppercase tracking-wider">注册时间</th>
            <th class="px-6 py-4 text-center text-xs font-bold uppercase tracking-wider">操作</th>
          </tr>
        </thead>
        <tbody class="bg-white divide-y divide-gray-100">
          {% for user in users %}
          <tr class="table-row">
            <td class="px-6 py-4 whitespace-nowrap">
              <div class="flex items-center">
                <div class="w-12 h-12 bg-gradient-to-br from-primary to-accent rounded-full flex items-center justify-center text-white font-bold mr-3 shadow-md">
                  {{ user.username[0].upper() }}
                </div>
                <div>
                  <span class="text-sm font-bold text-gray-900 block">{{ user.username }}</span>
                  <span class="text-xs text-gray-500">ID: #{{ user.id }}</span>
                </div>
              </div>
            </td>
            <td class="px-6 py-4">
              <div class="text-sm space-y-1">
                <div class="flex items-center text-gray-900">
                  <i class="fas fa-envelope text-primary mr-2 w-4"></i>
                  <span class="truncate max-w-[200px]">{{ user.email }}</span>
                </div>
                <div class="flex items-center text-gray-600">
                  <i class="fas fa-phone text-primary mr-2 w-4"></i>
                  {{ user.phone or '未设置' }}
                </div>
              </div>
            </td>
            <td class="px-6 py-4 whitespace-nowrap">
              <form method="POST" action="{{ url_for('admin.update_user_role', user_id=user.id) }}" class="inline">
                <select name="role" onchange="this.form.submit()"
                        class="badge {% if user.role == 'admin' %}badge-admin{% else %}badge-user{% endif %} cursor-pointer hover:shadow-md transition-all border-0">
                  <option value="user" {% if user.role == 'user' %}selected{% endif %}>👤 用户</option>
                  <option value="admin" {% if user.role == 'admin' %}selected{% endif %}>🔑 管理员</option>
                </select>
              </form>
            </td>
            <td class="px-6 py-4 whitespace-nowrap">
              <div class="text-sm">
                <div class="text-gray-900 font-semibold">
                  <i class="fas fa-calendar text-primary mr-1"></i>
                  {{ user.created_at.strftime('%Y-%m-%d') if user.created_at else '-' }}
                </div>
                <div class="text-xs text-gray-500 mt-1">
                  {{ user.created_at.strftime('%H:%M:%S') if user.created_at else '' }}
                </div>
              </div>
            </td>
            <td class="px-6 py-4 whitespace-nowrap">
              <div class="flex items-center justify-center space-x-2">
                <button type="button" onclick="editUser({{ user.id }})" 
                        data-user-id="{{ user.id }}"
                       >
                  <i class="fas fa-edit mr-1"></i>编辑
                </button>
                <button type="button" onclick="deleteUser({{ user.id }}, '{{ user.username }}')" 
                        data-user-id="{{ user.id }}"
                        >
                  <i class="fas fa-trash mr-1"></i>删除
                </button>
              </div>
            </td>
          </tr>
          {% endfor %}</tbody>
      </table>
    </div>
    <!-- 分页 -->
    {% if total_pages > 1 %}
    <div class="px-6 py-4 bg-gradient-to-r from-gray-50 to-blue-50 border-t border-gray-200">
      <div class="flex flex-col md:flex-row items-center justify-between gap-4">
        <div class="text-sm text-gray-700 font-medium">
          <i class="fas fa-info-circle text-primary mr-1"></i>
          显示 <span class="text-primary font-bold">{{ start_item }}</span> - <span class="text-primary font-bold">{{ end_item }}</span> 条，共 <span class="text-primary font-bold">{{ total_items }}</span> 条
        </div>
        <div class="flex flex-wrap gap-2 justify-center">
          {% if current_page > 1 %}
          <a href="?page={{ current_page - 1 }}{% if search_query %}&search={{ search_query }}{% endif %}{% if role_filter != 'all' %}&role={{ role_filter }}{% endif %}" 
             >
            <i class="fas fa-chevron-left mr-1"></i>上一页
          </a>
          {% endif %}
          
          {% for page in page_range %}
            {% if page == '...' %}
              <span class="px-3 py-2 text-gray-500">…</span>
            {% elif page == current_page %}
              <span class="px-4 py-2 bg-gradient-to-r from-primary to-accent text-white rounded-lg shadow-md font-bold">{{ page }}</span>
            {% else %}
              <a href="?page={{ page }}{% if search_query %}&search={{ search_query }}{% endif %}{% if role_filter != 'all' %}&role={{ role_filter }}{% endif %}" 
                >{{ page }}</a>
            {% endif %}
          {% endfor %}
          
          {% if current_page < total_pages %}
          <a href="?page={{ current_page + 1 }}{% if search_query %}&search={{ search_query }}{% endif %}{% if role_filter != 'all' %}&role={{ role_filter }}{% endif %}" 
            >
            下一页<i class="fas fa-chevron-right ml-1"></i>
          </a>
          {% endif %}
        </div>
      </div>
    </div>
    {% endif %}
    {% else %}
    <div class="p-16 text-center">
      <i class="fas fa-users text-8xl text-gray-300 mb-6"></i>
      <p class="text-gray-500 text-xl font-semibold mb-2">暂无用户数据</p>
      <p class="text-gray-400">尝试调整搜索条件或筛选条件</p>
    </div>
    {% endif %}
  </div>
</div>

<!-- 编辑用户模态框 -->
<div id="editUserModal" class="modal-overlay">
  <div class="modal-content">
    <div class="p-6">
      <div class="flex justify-between items-center mb-6 pb-4 border-b-2 border-primary">
        <div>
          <h3 class="text-2xl font-bold text-gray-900">
            <i class="fas fa-user-edit text-primary mr-2"></i>编辑用户信息
          </h3>
          <p class="text-sm text-gray-500 mt-1">修改用户的基本信息和权限</p>
        </div>
        <button onclick="closeEditModal()" class="text-gray-400 hover:text-gray-600 transition-colors">
          <i class="fas fa-times text-2xl"></i>
        </button>
      </div>
      <form id="editUserForm">
        <input type="hidden" id="editUserId" name="user_id">
        <div class="space-y-4">
          <!-- 用户ID显示（只读） -->
          <div>
            <label class="block text-sm font-semibold text-gray-700 mb-2">
              <i class="fas fa-hashtag text-primary mr-1"></i>用户ID
            </label>
            <input type="text" id="editUserIdDisplay" readonly
                   class="w-full px-4 py-2.5 border-2 border-gray-200 rounded-lg bg-gray-50 text-gray-600 cursor-not-allowed"
                   placeholder="系统自动生成">
          </div>
          <div>
            <label class="block text-sm font-semibold text-gray-700 mb-2">
              <i class="fas fa-user text-primary mr-1"></i>用户名
            </label>
            <input type="text" id="editUsername" required
                   class="w-full px-4 py-2.5 border-2 border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent transition-all"
                   placeholder="请输入用户名">
          </div>
          <div>
            <label class="block text-sm font-semibold text-gray-700 mb-2">
              <i class="fas fa-envelope text-primary mr-1"></i>邮箱
            </label>
            <input type="email" id="editEmail" required
                   class="w-full px-4 py-2.5 border-2 border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent transition-all"
                   placeholder="请输入邮箱地址">
          </div>
          <div>
            <label class="block text-sm font-semibold text-gray-700 mb-2">
              <i class="fas fa-phone text-primary mr-1"></i>电话
            </label>
            <input type="tel" id="editPhone"
                   class="w-full px-4 py-2.5 border-2 border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent transition-all"
                   placeholder="请输入电话号码(可选)">
          </div>
          <div>
            <label class="block text-sm font-semibold text-gray-700 mb-2">
              <i class="fas fa-shield-alt text-primary mr-1"></i>角色
            </label>
            <select id="editRole" class="w-full px-4 py-2.5 border-2 border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary transition-all">
              <option value="user">👤 普通用户</option>
              <option value="admin">🔑 管理员</option>
            </select>
          </div>
        </div>
        <div class="flex justify-end space-x-3 mt-8 pt-4 border-t border-gray-200">
          <button type="button" onclick="closeEditModal()" 
                  class="px-6 py-2.5 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition-all font-medium">
            <i class="fas fa-times mr-1"></i>取消
          </button>
          <button type="submit" 
                  class="px-6 py-2.5 bg-gradient-to-r from-primary to-accent text-white rounded-lg hover:shadow-lg transition-all font-medium">
            <i class="fas fa-check mr-1"></i>保存修改
          </button>
        </div>
      </form>
    </div>
  </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
// Toast 通知函数
function showToast(message, type = 'info') {
    const toast = document.createElement('div');
    const bgColors = {
        'success': 'bg-green-500',
        'error': 'bg-red-500',
        'info': 'bg-blue-500',
        'warning': 'bg-yellow-500'
    };
    
    toast.className = `fixed top-4 right-4 ${bgColors[type] || bgColors.info} text-white px-6 py-3 rounded-lg shadow-lg z-50 transform transition-all duration-300`;
    toast.innerHTML = `
        <div class="flex items-center space-x-2">
            <i class="fas fa-${type === 'success' ? 'check-circle' : type === 'error' ? 'exclamation-circle' : 'info-circle'}"></i>
            <span>${message}</span>
        </div>
    `;
    
    document.body.appendChild(toast);
    
    // 动画显示
    setTimeout(() => {
        toast.style.transform = 'translateX(0)';
    }, 10);
    
    // 3秒后自动消失
    setTimeout(() => {
        toast.style.transform = 'translateX(400px)';
        setTimeout(() => toast.remove(), 300);
    }, 3000);
}

// 加载遮罩
function showLoading(show = true) {
    let overlay = document.getElementById('loadingOverlay');
    if (show) {
        if (!overlay) {
            overlay = document.createElement('div');
            overlay.id = 'loadingOverlay';
            overlay.className = 'fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center';
            overlay.innerHTML = `
                <div class="bg-white rounded-lg p-8 shadow-2xl">
                    <div class="flex flex-col items-center">
                        <i class="fas fa-spinner fa-spin text-4xl text-primary mb-4"></i>
                        <p class="text-gray-700 font-medium">处理中...</p>
                    </div>
                </div>
            `;
            document.body.appendChild(overlay);
        }
        overlay.style.display = 'flex';
    } else {
        if (overlay) {
            overlay.style.display = 'none';
        }
    }
}

// 编辑用户
function editUser(userId) {
    console.log('编辑用户 ID:', userId);
    
    if (!userId) {
        showToast('无效的用户ID', 'error');
        return;
    }
    
    showLoading(true);
    
    // 获取用户信息
    fetch(`/admin/api/users/${userId}`)
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            showLoading(false);
            
            if (data.success) {
                console.log('用户数据:', data.user);
                document.getElementById('editUserId').value = data.user.id;
                document.getElementById('editUserIdDisplay').value = '#' + data.user.id;
                document.getElementById('editUsername').value = data.user.username;
                document.getElementById('editEmail').value = data.user.email;
                document.getElementById('editPhone').value = data.user.phone || '';
                document.getElementById('editRole').value = data.user.role;
                document.getElementById('editUserModal').classList.add('active');
            } else {
                showToast('获取用户信息失败：' + data.message, 'error');
            }
        })
        .catch(error => {
            showLoading(false);
            console.error('Error:', error);
            showToast('请求失败，请重试', 'error');
        });
}

// 关闭编辑模态框
function closeEditModal() {
    document.getElementById('editUserModal').classList.remove('active');
}

// 提交编辑表单
document.getElementById('editUserForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const userId = document.getElementById('editUserId').value;
    
    if (!userId) {
        showToast('用户ID丢失，请重新打开编辑页面', 'error');
        return;
    }
    
    const userData = {
        username: document.getElementById('editUsername').value.trim(),
        email: document.getElementById('editEmail').value.trim(),
        phone: document.getElementById('editPhone').value.trim(),
        role: document.getElementById('editRole').value
    };
    
    // 验证
    if (!userData.username || !userData.email) {
        showToast('用户名和邮箱不能为空', 'warning');
        return;
    }
    
    console.log('更新用户:', userId, userData);
    showLoading(true);
    
    fetch(`/admin/api/users/${userId}`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(userData)
    })
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
    })
    .then(data => {
        showLoading(false);
        
        if (data.success) {
            showToast('用户信息更新成功', 'success');
            closeEditModal();
            setTimeout(() => location.reload(), 1000);
        } else {
            showToast('更新失败：' + data.message, 'error');
        }
    })
    .catch(error => {
        showLoading(false);
        console.error('Error:', error);
        showToast('请求失败，请重试', 'error');
    });
});

// 删除用户
function deleteUser(userId, username) {
    if (!userId) {
        showToast('无效的用户ID', 'error');
        return;
    }
    
    if (!confirm(`确定要删除用户 "${username}" 吗？\n\n此操作不可恢复！`)) {
        return;
    }
    
    showLoading(true);
    
    fetch(`/admin/api/users/${userId}`, {
        method: 'DELETE'
    })
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
    })
    .then(data => {
        showLoading(false);
        
        if (data.success) {
            showToast('用户已删除', 'success');
            setTimeout(() => location.reload(), 1000);
        } else {
            showToast('删除失败：' + data.message, 'error');
        }
    })
    .catch(error => {
        showLoading(false);
        console.error('Error:', error);
        showToast('请求失败，请重试', 'error');
    });
}

// 点击遮罩层关闭模态框
document.getElementById('editUserModal').addEventListener('click', function(e) {
    if (e.target === this) {
        closeEditModal();
    }
});

// ESC键关闭模态框
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        const modal = document.getElementById('editUserModal');
        if (modal.classList.contains('active')) {
            closeEditModal();
        }
    }
});

// 页面加载完成后的调试
document.addEventListener('DOMContentLoaded', function() {
    console.log('=== 用户管理页面已加载 ===');
    console.log('页面中的编辑按钮数量:', document.querySelectorAll('[data-user-id]').length);
    
    // 打印所有用户ID
    document.querySelectorAll('[data-user-id]').forEach((btn, index) => {
        const userId = btn.getAttribute('data-user-id');
        console.log(`按钮 ${index + 1} - 用户ID:`, userId);
    });
});
</script>
{% endblock %}